from sqlalchemy import insert, select
from forward.dependencies.database import db
from forward.exceptions.base import AppException
from forward.http_base import HttpResp
from forward.model.schemas.contact import ContactAddInSchema, ContactSchema
from forward.model.tables.contact import ContactModel


class ContactORM:
    @classmethod
    async def get_one_by_id(cls, id: int) -> ContactSchema | None:
        statement = select(ContactModel).where(ContactModel.id == id)
        record = await db.fetch_one(statement)
        return ContactSchema.model_validate(record, from_attributes=True)

    @classmethod
    async def get_one_by_params(cls, **kwargs) -> ContactSchema | None:
        where = []
        for k, v in kwargs.items():
            where.append(getattr(ContactModel, k) == v)
        statement = select(ContactModel).where(*where)
        record = await db.fetch_one(statement)
        if not record:
            return None
        return ContactSchema.model_validate(record, from_attributes=True)

    @classmethod
    async def insert(cls, add_in: ContactAddInSchema) -> int | None:
        statement = insert(ContactModel).values(**add_in.model_dump())
        id = await db.execute(statement)
        return id
